<template>
  <div>
    <div>
      <el-container>
        <el-main>
          <!--Team Maintenance-->
          <el-header class="header-class" height="22">
            <div class="header-text">Team Maintenance</div>
          </el-header>
          <div class="panel-border">
            <div class="search-panel">
              <el-form>
                <el-form-item label="Team Name:" label-width="130px" class="search-form-item">
                  <el-input :size="'mini'" v-model="searchTeamName" style="width: 300px; margin-right: 10px"></el-input>
                  <el-button size="mini" @click="search">Search</el-button>
                  <el-button size="mini" @click="reset">Reset</el-button>
                </el-form-item>
              </el-form>
            </div>
            <el-row>
              <div class="add-button-class">
                <el-button @click="handleTeamAdd">Add Team</el-button>
              </div>
            </el-row>
            <el-table border class="table" :data="teamList" @row-click="onRowClick" style="width: 98%"
                      empty-text="No record found" :highlight-current-row=true>
              <el-table-column label="#" type="index" width="40" :index="indexCalculate">
              </el-table-column>
              <el-table-column prop="name" label="Team Name">
              </el-table-column>
              <el-table-column prop="desc" label="Team Description">
              </el-table-column>
              <el-table-column prop="createdAt" label="Created AT">
              </el-table-column>
              <el-table-column prop="createdBy.domainId" label="Created By">
              </el-table-column>
              <el-table-column prop="updatedAt" label="Last Updated At">
              </el-table-column>
              <el-table-column prop="updatedBy.domainId" label="Last Updated By">
              </el-table-column>
              <el-table-column label="Action">
                <template slot-scope="scope">
                  <el-button size="mini" @click.stop="handleTeamEdit(scope.$index, scope.row)" icon="el-icon-edit">Edit</el-button>
                  <el-button size="mini" type="danger" @click.stop="handleTeamDelete(scope.$index, scope.row)" icon="el-icon-delete">Delete
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-container>
              <div class="pagination">
                <el-pagination layout="prev, pager, next" :total="totalTeam" :page-size="teamLimit"
                               @current-change="onTeamPageChange" :current-page="currentTeamPage">
                </el-pagination>
              </div>
            </el-container>
          </div>
        </el-main>
      </el-container>
      <el-container>
        <el-main>
          <!--Team Endorser Maintenance-->
          <el-header class="header-class" height="22">
            <div class="header-text">Team Endorser Maintenance</div>
          </el-header>
          <div class="panel-border">
            <el-row>
              <div class="add-button-class">
                <el-button @click="handleTeamEndorserAdd" v-show="this.selectedTeam.id">Add Endorser</el-button>
              </div>
            </el-row>
            <el-table border class="table" :data="teamEndorserList" style="width: 98%" empty-text="No record found"
                      :highlight-current-row=true>
              <el-table-column label="#" type="index" width="30">
              </el-table-column>
              <el-table-column prop="team" label="Team">
              </el-table-column>
              <el-table-column prop="users.displayName" label="Display Name">
              </el-table-column>
              <el-table-column prop="endorser" label="Endorser">
              </el-table-column>
              <el-table-column prop="createdAt" label="Created AT">
              </el-table-column>
              <el-table-column prop="createdBy.domainId" label="Created By">
              </el-table-column>
              <el-table-column prop="updatedAt" label="Last Updated At">
              </el-table-column>
              <el-table-column prop="updatedBy.domainId" label="Last Updated By">
              </el-table-column>
              <el-table-column label="Action">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="handleTeamEndorserDelete(scope.$index, scope.row)" icon="el-icon-delete">
                    Delete
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-main>
      </el-container>
    </div>
    <!--Edit Team Dialog-->
    <el-dialog title="Team" width="30%" :visible.sync="addTeamFormVisible">
      <el-form :model="newTeam" ref="editTeamForm" label-position="left" :rules="teamRules">
        <el-form-item label="Team Name:" label-width="200px" prop="name">
          <el-input v-model="newTeam.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="Team Description:" label-width="200px">
          <el-input v-model="newTeam.desc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCloseEditTeamDialog">Cancel</el-button>
        <el-button type="primary" v-show="this.isAddTeam" @click="onAddNewTeam('editTeamForm')">Add</el-button>
        <el-button type="primary" v-show="!this.isAddTeam" @click="onEditTeam('editTeamForm')" icon="el-icon-edit">Edit</el-button>
      </div>
    </el-dialog>
    <!--Edit Team Endorser Dialog-->
    <el-dialog title="Team Endorser" width="30%" :visible.sync="addTeamEndorserFormVisible">
      <el-form :model="newTeamEndorser" ref="editTeamEndorserForm" label-position="left" :rules="teamEndorserRules">
        <el-form-item label="Team:" label-width="200px">
          {{this.selectedTeam.name}}
        </el-form-item>
        <el-form-item label="Endorser:" label-width="200px" prop="endorser">
          <el-input v-model="newTeamEndorser.endorser" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCloseEditTeamEndorserDialog">Cancel</el-button>
        <el-button type="primary" @click="onAddNewTeamEndorser('editTeamEndorserForm')">Add</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import teamListService from '@/service/team'
import teamEndorserService from '@/service/teamEndorser'
import util from '@/common/js/util'

export default {
  data() {
    return {
      searchTeamName: '',
      newTeam: {
        name: '',
        desc: '',
        teamEndorsers: []
      },
      newTeamEndorser: {
        teamName: '',
        endorser: ''
      },
      teamList: [], // display
      teamEndorserList: [], // display
      selectedTeam: {},
      selectedTeamEndorser: {},
      isAddTeam: true,
      addTeamFormVisible: false,
      addTeamEndorserFormVisible: false,
      teamLimit: 6,
      totalTeam: 0,
      currentTeamPage: 1,
      teamRules: {
        name: [
          {required: true, message: 'Please input Team Name', trigger: 'blur'}
        ]
      },
      teamEndorserRules: {
        endorser: [
          {required: true, message: 'Please input Endorser DomainId', trigger: 'change'}
        ]
      }
    }
  },
  created() {
    let load = this.$loading()
    this.getTeams(1)
    load.close()
  },
  methods: {
    indexCalculate(index) {
      return (this.currentTeamPage - 1) * this.teamLimit + index + 1
    },
    async search() {
      let teamName = this.searchTeamName
      let teamNameSearchFilter = {
        fieldName: 'name',
        operator: 'LIKE',
        value: teamName
      }
      let searchFilters = []
      searchFilters.push(teamNameSearchFilter)
      this.getTeams(1, searchFilters)
    },
    async reset() {
      this.resetSearchBar()
      this.resetTeamList()
      this.cleanTeamEndorserList()
    },
    resetSearchBar() {
      this.searchTeamName = ''
    },
    async resetTeamList() {
      this.getTeams(1)
    },
    cleanTeamEndorserList() {
      this.teamEndorserList = []
    },
    async resetTeamEndorserList() {
      if (this.selectedTeam.id) {
        this.teamEndorserList = await teamListService.getTeamEndorserListByTeamId(this.selectedTeam.id)
      }
    },
    // Team Maintenance
    handleTeamAdd() {
      this.isAddTeam = true
      this.addTeamFormVisible = true
    },
    async onAddNewTeam(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await teamListService.addNewTeam(this.newTeam)
          this.addTeamFormVisible = false
          this.newTeam = {}
          this.reset()
        } else {
          return false
        }
      })
    },
    handleTeamEdit(index, row) {
      this.newTeam = util.deepClone(row)
      this.isAddTeam = false
      this.addTeamFormVisible = true
    },
    async onEditTeam(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await teamListService.updateTeam(this.newTeam)
          this.search()
          this.addTeamFormVisible = false
          this.newTeam = {}
        } else {
          return false
        }
      })
    },
    handleTeamDelete(index, row) {
      this.$confirm(`Are you sure you want to delete this Team ?`, 'Warning', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel',
        type: 'warning',
        callback: async (action) => {
          if (action === 'confirm') {
            await teamListService.deleteTeamById(row.id)
            this.reset()
          }
        }
      }).then(() => {
        this.$message({
          type: 'success',
          message: 'Delete successfully.'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel delete.'
        })
      })
    },
    onCloseEditTeamDialog() {
      this.addTeamFormVisible = false
      this.$refs.editTeamForm.resetFields()
      this.newTeam = {}
    },
    onTeamPageChange(page) {
      let teamNameSearchFilter = {
        fieldName: 'name',
        operator: 'LIKE',
        value: this.searchTeamName
      }
      let searchFilters = []
      searchFilters.push(teamNameSearchFilter)
      this.getTeams(page, searchFilters)
      this.currentTeamPage = page
      this.selectedTeam = {}
    },
    async onRowClick(row) {
      this.selectedTeam = row
      this.teamEndorserList = await teamListService.getTeamEndorserListByTeamId(this.selectedTeam.id)
    },
    async getTeams(page, searchFilters) {
      let query = {
        searchFilters: searchFilters,
        page: page,
        start: 0,
        limit: this.teamLimit
      }
      let result = await teamListService.getTeamsWithQuery(query)
      this.teamList = result.content
      this.totalTeam = result.totalElements
      this.teamEndorserList = []
    },
    // Team Endorser Maintenance
    handleTeamEndorserAdd() {
      this.addTeamEndorserFormVisible = true
      this.newTeamEndorser.teamName = this.selectedTeam.name
    },
    async onAddNewTeamEndorser(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let result = await teamEndorserService.addTeamEndorser(this.newTeamEndorser)
          if (result.data === null) {
            return false
          }
          this.addTeamEndorserFormVisible = false
          this.newTeamEndorser = {}
          this.$refs.editTeamEndorserForm.resetFields()
          this.resetTeamEndorserList()
        } else {
          return false
        }
      })
    },
    handleTeamEndorserDelete(index, row) {
      this.$confirm(`Are you sure you want to delete this Team Endorser ?`, 'Warning', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel',
        type: 'warning',
        callback: async (action) => {
          if (action === 'confirm') {
            await teamEndorserService.deleteTeamEndorserById(row.id)
            this.onRowClick(this.selectedTeam)
          }
        }
      }).then(() => {
        this.$message({
          type: 'success',
          message: 'Delete successfully.'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel delete.'
        })
      })
    },
    onCloseEditTeamEndorserDialog() {
      this.addTeamEndorserFormVisible = false
      this.$refs.editTeamEndorserForm.resetFields()
      this.newTeamEndorser = {}
    }
  }
}
</script>

<style scoped lang="scss">
  @import './../../common/css/base.scss';

  .add-button-class {
    margin-left: 15px;
    margin-top: 5px;
  }

  .pagination {
    align-items: center;
    margin-left: auto;
    margin-right: auto;
  }

  .panel-border {
    border: 1px solid $base-header-color;
  }

  .search-panel {
    height: 100px;
    margin: 10px;
    padding: 10px;
    border: 1px solid $base-header-color;
  }

  .table {
    margin: 15px;
  }

  .header-class {
    @include baseHeader(30px);
  }

  .header-text {
    color: #fff;
    padding-top: 5px;
    font-weight: bold;
  }

  .el-form-item.search-form-item {
    margin-bottom: 0;
  }
</style>
